#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <unistd.h>

using namespace std;

int main(int argc, char const *argv[])
{
	string line;
	ifstream logfile (".Down.log");
	ofstream filtered (".D.tmp");

	if(!filtered.is_open())
	{
		cout<< "Unable to create filtered file";
		return 1;
	}

	char down_size[30], speed[10];
	int perc = 0, start = 0, stop = 0;

	if(logfile.is_open())
	{
		while(true)
		{
			while( getline(logfile,line) )
			{
				start = 1;
	
				if(line[0] == '[' && line[1] == '#')
				{
					int i=0, j=0;
					size_t found = line.find(' ');

					for( i=found+1, j=0; line[i] != ' '; ++i,++j)
						down_size[j] = line[i];
					down_size[j] = '\0';
	
					found = line.find('(');
	
					if(found != string::npos)
					{
						char temp[3];
	
						for( i=found+1, j=0; line[i] != '%'; ++i,++j)
							temp[j] = line[i];
	
						perc = atoi(temp);
					}
					found = line.find('D');
	
					for( i=found+3, j=0; (line[i] != ' ' && line[i] != ']'); ++i,++j)
						speed[j] = line[i];
					speed[j] = '\0';
	
					filtered << perc;
					filtered << "\t" << down_size << "\t" << speed << endl;
				}

				size_t found = line.find("Download complete");

				if(found != string::npos)
				{
					stop = 1;
					filtered << "COMPLETE" << endl;
					break;
				}

				found = line.find("ERROR");
				if(found != string::npos)
				{
					stop = 1;
					filtered << "ERROR" << endl;
					break;
				}

			}
			if(stop == 1) break;
			if(!logfile.eof())	break;
			logfile.clear();
			usleep(300000);		//sleep for .3 sec

		}
	}

	else cout << "Error : Unable to open file";

	logfile.close();
	filtered.close();

	return 0;
}
